package win.devhu.onestation.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;

/**
 * 字符串处理
 * @author devhu
 *
 */
public class StringUtil {
	/**
	 * encrypt32 MD5 32位加密
	 * @param encryptStr
	 * @return String
	 */
	public String encrypt32(String encryptStr) {
		MessageDigest md5;
		try {
			md5 = MessageDigest.getInstance("MD5");
			byte[] md5Bytes = md5.digest(encryptStr.getBytes());
			StringBuffer hexValue = new StringBuffer();
			for (int i = 0; i < md5Bytes.length; i++) {
				int val = ((int) md5Bytes[i]) & 0xff;
				if (val < 16)
					hexValue.append("0");
				hexValue.append(Integer.toHexString(val));
			}
			encryptStr = hexValue.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return encryptStr;
	}

	
	/**
	 * base64 编码
	 * @param codeString
	 * @return
	 */
	public String base64Encode(String codeString) {
		Base64.Encoder encoder = Base64.getEncoder();
		String encodedString = encoder.encodeToString(
				codeString.getBytes(StandardCharsets.UTF_8));
		return encodedString;
	}
	
	/**
	 * base64 解码
	 * @param encodedString
	 * @return
	 */
	public String base64Decode(String encodedString) {
		Base64.Decoder decoder = Base64.getDecoder();
		byte[] decodedByteArray = decoder.decode(encodedString);
		String decodedString = new String(decodedByteArray);
		return decodedString;
	}
	
	/**
	 * 获取时间戳
	 * @return
	 */
	public String timeMillis() {
		//System.out.println(System.currentTimeMillis() / 1000); //时间戳精确到秒
		return String.valueOf(System.currentTimeMillis());	//精确到毫秒
	}
	
}
